`include "include.v"

module seg7_top (
  input  wire       clk,
  input  wire       rst_n,
  input  wire       set,
  input  wire [3:0] seg_in,
  input  wire [1:0] anode_in,
  output reg  [3:0] anode_out,
  output reg  [6:0] seg_out,
  output wire       dp
);

// 7-seg decoded numbers
wire [6:0] seg_a;   // output for first  7-sig display
wire [6:0] seg_b;   // output for second 7-sig display
wire [6:0] seg_c;   // output for third  7-seg display
wire [6:0] seg_d;   // output for fourth 7-sig display

// Binary numbers
reg [3:0] bin_seg_a;
reg [3:0] bin_seg_b;
reg [3:0] bin_seg_c;
reg [3:0] bin_seg_d;

// A counter to select which digit to light up
reg [1:0] anode_sel;

assign dp = ~1'b0;

// Flip flops to hold the bin_seg_*
always @(posedge clk or negedge rst_n) begin
  if (!rst_n) begin
    bin_seg_a <= 4'h0;
    bin_seg_b <= 4'h0;
    bin_seg_c <= 4'h0;
    bin_seg_d <= 4'h0;
  end else begin
    if (set) begin
      case (anode_in)
        2'b00 : bin_seg_a <= seg_in;
        2'b01 : bin_seg_b <= seg_in;
        2'b10 : bin_seg_c <= seg_in;
        2'b11 : bin_seg_d <= seg_in;
      endcase
    end
  end
end

// Up-counter for anode_sel
always @(posedge clk or negedge rst_n) begin
  if (!rst_n) begin
    anode_sel <= 4'h0;
  end else begin
    anode_sel <= anode_sel + 1'b1;
  end
end

// Select the outputs
always @(*) begin
  case (anode_sel)
    2'h0 :    seg_out = seg_a;
    2'h1 :    seg_out = seg_b;
    2'h2 :    seg_out = seg_c;
    2'h3 :    seg_out = seg_d;
    default:  seg_out = `SEG_0;
  endcase
end

always @(*) begin
  case (anode_sel)
    2'h0 :    anode_out = `AN_1;
    2'h1 :    anode_out = `AN_2;
    2'h2 :    anode_out = `AN_3;
    2'h3 :    anode_out = `AN_4;
    default : anode_out = `AN_1;
  endcase
end

// Decoders
seg7_decode a_seg7_decode (
  .en(1'b1),
  .seg_in(bin_seg_a),
  .seg_out(seg_a)
);

seg7_decode b_seg7_decode (
  .en(1'b1),
  .seg_in(bin_seg_b),
  .seg_out(seg_b)
);

seg7_decode c_seg7_decode (
  .en(1'b1),
  .seg_in(bin_seg_c),
  .seg_out(seg_c)
);

seg7_decode d_seg7_decode (
  .en(1'b1),
  .seg_in(bin_seg_d),
  .seg_out(seg_d)
);

endmodule
